package com.gede.web.esael.Controller;

import org.ofdrw.core.action.Actions;
import org.ofdrw.gm.cert.PKCS12Tools;
import org.ofdrw.gm.ses.v4.SESeal;
import org.ofdrw.layout.OFDDoc;
import org.ofdrw.layout.element.Paragraph;
import org.ofdrw.reader.OFDReader;
import org.ofdrw.sign.OFDSigner;
import org.ofdrw.sign.SignMode;
import org.ofdrw.sign.signContainer.SESV4Container;
import org.ofdrw.sign.stamppos.RidingStampPos;
import org.ofdrw.sign.stamppos.Side;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.cert.Certificate;

@RestController
public class TestController {
    @GetMapping("/demo")
    public String demo(){
    Actions a=new Actions();
        return "hello !!";
    }

    /**
     *
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */
    @GetMapping("/test")
    public String rideRight() throws GeneralSecurityException, IOException {
        Path userP12Path = Paths.get("H:\\esael\\src\\test\\resources", "USER.p12");
        Path sealPath = Paths.get("H:\\esael\\src\\test\\resources", "UserV4.esl");

        PrivateKey prvKey = PKCS12Tools.ReadPrvKey(userP12Path, "private", "777777");
        Certificate signCert = PKCS12Tools.ReadUserCert(userP12Path, "private", "777777");
        SESeal seal = SESeal.getInstance(Files.readAllBytes(sealPath));

        Path src = Paths.get("H:\\esael\\src\\test\\resources", "VPage7.ofd");
        Path out = Paths.get("H:\\esael\\src\\test\\resources/1/V4RideRight.ofd");
        // 1. 构造签名引擎
        try (OFDReader reader = new OFDReader(src);
             OFDSigner signer = new OFDSigner(reader, out)) {
            SESV4Container signContainer = new SESV4Container(prvKey, seal, signCert);
            // 2. 设置签名模式
            signer.setSignMode(SignMode.WholeProtected);
            // 3. 设置签名使用的扩展签名容器
            signer.setSignContainer(signContainer);
            // 4. 设置显示位置
            signer.addApPos(new RidingStampPos(Side.Right, 40, 40));
            // 5. 执行签名
            signer.exeSign();
            // 6. 关闭签名引擎，生成文档。
        }
        System.out.println(">> 生成文件位置: " + out.toAbsolutePath().toAbsolutePath());
        return "成功了！";
    }


    @GetMapping("/create")
    public String createOfd() throws IOException {
        Path path = Paths.get("H:\\esael\\src\\test\\resources\\1\\HelloWorld.ofd");
        try (OFDDoc ofdDoc = new OFDDoc(path)) {
            Paragraph p = new Paragraph("你好呀，OFD Reader&Writer！");
            ofdDoc.add(p);
        }
        System.out.println("生成文档位置: " + path.toAbsolutePath());
        return "生成文档位置: " +path.toAbsolutePath();
    }
}
